import 'dart:convert';

import 'package:aitao_flutter/config/config.dart';
import 'package:aitao_flutter/im/im_manager.dart';
import 'package:aitao_flutter/im/im_notification_manager.dart';
import 'package:aitao_flutter/language/language.dart';
import 'package:aitao_flutter/login/page/code_login_page.dart';
import 'package:aitao_flutter/request/api.dart';
import 'package:aitao_flutter/request/requestManager.dart';
import 'package:aitao_flutter/routes/routes.dart';
import 'package:aitao_flutter/tab/views/tab.dart';
import 'package:aitao_flutter/utils/sp_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get_navigation/src/root/get_material_app.dart';
import 'package:get_storage/get_storage.dart';
import 'package:get/get.dart';
import 'package:netease_corekit_im/router/imkit_router.dart';
import 'package:nim_chatkit_ui/chat_kit_client.dart';
import 'package:nim_contactkit_ui/contact_kit_client.dart';
import 'package:nim_conversationkit_ui/conversation_kit_client.dart';
import 'package:nim_searchkit_ui/search_kit_client.dart';
import 'const/common_const.dart';

void main() async {
  await GetStorage.init();
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    initPlugins();
    return MaterialApp(
      title: CommonStringConst.appName,
      routes: IMKitRouter.instance.routes,
      // navigatorObservers: [AppRouteObserver().routeObserver],
      // 3. 添加支持的语言
      // supportedLocales: IMKitClient.supportedLocales,
      supportedLocales: const [
        // Locale('en', 'US'), // 英语
        Locale('zh', 'CN'), // 中文
        // 添加其他支持的语言
      ],

      // 4. 添加模块支持
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
        ConversationKitClient.delegate,
        ChatKitClient.delegate,
        ContactKitClient.delegate,
        SearchKitClient.delegate,

        // GlobalWidgetsLocalizations.delegate,
      ],
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: false,
      ),
      // home: const MyHomePage(title: 'Flutter Demo Home Page'),
      home: ScreenUtilInit(
        designSize: const Size(375, 667),
        // designSize: const Size(532, 951), // 1。42
        minTextAdapt: true,
        builder: (BuildContext context, Widget? child) {
          return GetMaterialApp(
              routes: IMKitRouter.instance.routes,
              getPages: Routes.routePage,
              title: CommonStringConst.appName,
              debugShowCheckedModeBanner: false,
              locale: SpUtil.getLanguage(),
              fallbackLocale: const Locale('zh', 'CN'), // 在配置错误的情况下使用该语言]
              translations: Language(),
              builder: EasyLoading.init(),
              theme: ThemeData(
                  primarySwatch: Colors.blue,
                  highlightColor: const Color.fromRGBO(0, 0, 0, 0), // 去除点击效果
                  splashColor: const Color.fromRGBO(0, 0, 0, 0)),
              home: MediaQuery(
                data: MediaQuery.of(context).copyWith(textScaleFactor: 1.0),
                child: getLoginStatus() ? const Tabs() : const CodeLoginPage(),
              ));
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    firstActivate();
    IMManager.getInstance()!.initIM();
    getServerConfig();
    initThird();
    // 设置App在前台的运行状态
    SpUtil.saveAppLifeState(true);
    // 设置App视频状态
    SpUtil.saveIsVideo(false);
    if (SpUtil.getToken() != '') {
      getAppConfig();
      getUploadConfig();
    }
    // 初始化IM监听
    IMNotificationManager().init();
  }

  void firstActivate() {
    // 是否首次安装,需要初始化部分数据
    if (SpUtil.getFirstLaunch() == true) {
      SpUtil.saveSystemVoiceStatus(true);
      SpUtil.saveSystemVibrationStatus(true);
      SpUtil.saveFirstLaunch(false);
      // 设置App默认语言
      SpUtil.saveLanguage('zh_CN');
    }
  }

  void initThird() {
    Fluwx fluwx = Fluwx();
    fluwx.registerApi(
        appId: AppConfig.wxAppKey, universalLink: AppConfig.universalLink);
  }

  void initPlugins() {
    ChatKitClient.init();
    // TeamKitClient.init();
    ConversationKitClient.init();
    ContactKitClient.init();
    SearchKitClient.init();
  }

  void getServerConfig() async {
    var result = await RequestManager().post(API.getServerConfig);
    SpUtil.saveServerConfig(result['data']);
  }

  void getAppConfig() async {
    var result = await RequestManager().post(API.getAppConfig);
    if (result != null && result['code'] == 0) {
      SpUtil.saveAppConfig(result['data']);
    }
  }

  void getUploadConfig() async {
    var result =
        await RequestManager().get(API.getUploadConfig, hasCode: false);
    if (result != null) {
      try {
        Map<String, dynamic> jsonMap = jsonDecode(result);
        SpUtil.saveOssConfig(jsonMap);
        debugPrint('字符串是有效的JSON格式');
      } catch (e) {
        debugPrint('字符串不是有效的JSON格式');
      }
    }
  }

  bool getLoginStatus() {
    return GetStorage().read("token") != null;
  }
}
